#!/bin/bash

set -e

# Defaults
sprout_hostname=sprout.$(config-get zone)
hs_hostname=homestead.$(config-get zone):8888
hs_provisioning_hostname=homestead.$(config-get zone):8889
xdms_hostname=
ralf_hostname=ralf.$(config-get zone):10888
enum_server=

# Import existing configuration
[ ! -f /etc/clearwater/config ] || . /etc/clearwater/config

# Apply new configuration
home_domain=$(config-get zone)
[ "$relation-name" != "cscf" ] || [ "$(relation-get public-address)" = "" ] || sprout_hostname=$(relation-get public-address)
[ "$relation-name" != "ralf-ctf" ] || [ "$(relation-get public-address)" = "" ] || ralf_hostname=$(relation-get public-address):9888
sas_server=$(config-get sas)
local_ip=$(unit-get private-address)
public_ip=$(unit-get public-address)
public_hostname=bono-$(cut -d/ -f2 <<< $JUJU_UNIT_NAME).$(config-get zone)
turn_workaround=$(config-get turn_workaround)
cdf=$(config-get cdf)
target_latency_us=$(config-get target_latency_us)

# Write configuration back
mkdir -p /etc/clearwater
cat >/etc/clearwater/config <<EOF
# Deployment definitions
home_domain=$home_domain
sprout_hostname=$sprout_hostname
hs_hostname=$hs_hostname
hs_provisioning_hostname=$hs_provisioning_hostname
xdms_hostname=$xdms_hostname
ralf_hostname=$ralf_hostname
sas_server=$sas_server
enum_server=$enum_server
cdf_identity=$cdf

# Local IP configuration
local_ip=$local_ip
public_ip=$public_ip
public_hostname=$public_hostname

# Keys
turn_workaround=$turn_workaround
target_latency_us=$target_latency_us
EOF
